<?php
namespace Orx\Mailer\MailBox\Message\Editor;
/**
 * Default new message editor
 * 
 * @author Xavier VILAIN
 * @package Orx\Mailer\MailBox\Message\Editor
 * 
 */
use Fox\Html\Wrapper;
use Fox\Html\DropList\Token;
use Orx\Mailer\Messages;

class Classic extends \Fox\Html\Input {
	
	/**
	 * Mode New Messages
	 * @var int
	 */
	const RENDERING_MODE_NEW_MESSAGE = 1;
	
	/**
	 * Mode Answer
	 * @var int
	 */
	const RENDERING_MODE_ANSWER = 2;

	/**
	 * Forward
	 * @var int
	 */
	const RENDERING_MODE_FORWARD = 3;
		
	/**
	 * Mail Message
	 * @var \Orx\Mailer\MailBox\Message
	 */
	protected $message = null;
	
	/**
	 * Screen
	 * @var \Fox\Html\Screen
	 */
	protected $screen = null;
	
	/**
	 * Header Part
	 * @var \Fox\Html\Wrapper
	 */
	protected $headerPart = null;
	
	/**
	 * Constructor
	 * @param \Orx\Mailer\MailBox\Message $message
	 */
	public function __construct(\Orx\Mailer\MailBox\Message $message = null,$renderingMode = null) {
		$this->message = $message;
		$this->renderingMode($renderingMode);
		parent::__construct('message-editor');
	}
	
	/**
	 * Screen
	 * @return \Fox\Html\Screen
	 */
	public function screen() {
		if(empty($this->screen)) {
			$this->screen = new \Fox\Html\Screen('answer-screen',
											'send',
											null,
											true,
											\Fox\Generator::ajaxReload('viewer-container'));
			$this->screen->buttonOnBottom(false);
		}
		return $this->screen;
	}
	
	/**
	 * Get Header Input Block
	 * @return \Fox\Html\Wrapper
	 */
	public function headerPart() {
		if(empty($this->headerPart)) {
			$this->headerPart = new Wrapper('headerPart','');
			// Sender
			$this->headerPart
					->add(new \Fox\Html\DropList('sender',false,false,true))
					->label(Msg(Messages::BUNDLE,Messages::FROM_USER))
					->options(\User::current()->personalMailers(),'email','email');
			// Receivers
			$this->headerPart
					->add(new \Fox\Html\DropList\Token('receivers',false,false,true))
					->behaviors(\Fox\Behaviors::value('rd4'))
					->size(\Fox\Html\Input::SIZE_XXLARGE)
					->label(Msg(Messages::BUNDLE,Messages::RECEIVERS))
					->source(\Fox\Generator::url('contacts','emails','autocomplete'));
			// Cs Receivers
			$this->headerPart
					->add(new \Fox\Html\DropList\Token('receivers_ccs',false,false,false))
					->behaviors(\Fox\Behaviors::value('rd4'))
					->size(\Fox\Html\Input::SIZE_XXLARGE)
					->label(Msg(Messages::BUNDLE,Messages::RECEIVERS_CC))
					->source(\Fox\Generator::url('contacts','emails','autocomplete'));
			// Cci Receivers
			$this->headerPart
					->add(new \Fox\Html\DropList\Token('receivers_cci',false,false,false))
					->behaviors(\Fox\Behaviors::value('rd4'))
					->size(\Fox\Html\Input::SIZE_XXLARGE)
					->label(Msg(Messages::BUNDLE,Messages::RECEIVERS_CCI))
					->source(\Fox\Generator::url('contacts','emails','autocomplete'));
			// Subject
			$this->headerPart
					->add(new \Fox\Html\Input('subject',false))
					->size(\Fox\Html\Input::SIZE_XXLARGE)
					->label(Msg(Messages::BUNDLE,Messages::SUBJECT));
			// Attachement
			//@TODO
			// Hidden Parts
			$this->headerPart->add(new \Fox\Html\Input('type',false))
					->hide();
			$this->headerPart->add(new \Fox\Html\Input('parentid',false))
					->hide();
			$this->headerPart->add(new \Fox\Html\Input('answerid',false))
					->hide();
		}
		return $this->headerPart;
	}
	
	/**
	 * 
	 * Render the editor
	 * @return 
	 */
	public function render($newMessageMode = false) {
		$html = null;
		$receivers = null;
		$receivers_cc = null;
		$receivers_cci = null;
		$data = $this->message->getFullFormatedData();
		if($this->message->exists()) {
			
		} else {
			$data['type'] = $this->renderingMode;
		}
		$messageContent = $this->message->content();
		$subject = $this->message->subject;
		
		
		$messageTextBox = new \Fox\Html\TextArea('answer-editor-textbox');
		$messageTextBox->wysiwygEditor(true);
		if(\Xview::instance()->ajax()) {
			$html .= \Fox\Ressources::instance()->dump(false);
		} else {
			$html .= \Fox\Ressources::instance()->dump();
		}
		
		// HTML
		$htmlAnswer = '
			<div class="btn-toolbar" style="padding-top: 10px;margin-top:0">
				<input type="hidden" value="'.$this->message->getId().'" name="anwserid">
				<input type="submit" name="send" class="btn  btn-warning" id="act-send" value="'.Msg(Messages::BUNDLE,Messages::SEND).'">
				<input type="submit" name="save" class="btn" id="act-save" value="'.Msg(Messages::BUNDLE,Messages::SAVE).'">
				<input type="submit" name="delete" class="btn" id="act-delete" value="'.Msg(Messages::BUNDLE,Messages::DELETE).'">
			</div>
			<div class="tab-content" style="border:none">';
	
		// Cc's
		if(empty($data['receivers_ccs'])) {
			$this->headerPart()->item('receivers_ccs')->hide();
		}
		if(empty($data['receivers_cci'])) {
			$this->headerPart()->item('receivers_cci')->hide();
		}
		if($this->renderingMode == self::RENDERING_MODE_ANSWER) {
			$this->headerPart()->item('subject')->hide();
		}
		$this->headerPart()->initialize($data);
		$htmlAnswer .= $this->headerPart()->render();
		$htmlAnswer .= '</div>';
		
		$htmlAnswer .= '<div class="answer-actions">
				<a href="javacript:void()" id="adcc">'.Msg(Messages::BUNDLE,Messages::ADD_CC).'</a>
				<a href="javacript:void()" id="adcci">'.Msg(Messages::BUNDLE,Messages::ADD_CCI).'</a>';
		
		//$htmlAnswer .= '<a href="javacript:void()" id="addattachement">'.Msg(Messages::BUNDLE,Messages::ADD_ATTACHEMENT).'</a>';
		if($this->renderingMode == self::RENDERING_MODE_ANSWER) {
				$htmlAnswer .= '<a href="javacript:void()" id="changesubject">'.Msg(Messages::BUNDLE,Messages::CHANGE_SUBJECT).'</a>';
		}
		$htmlAnswer .= '</div>
			<div class="answer-editor">
			<textarea id="answer_editor_textbox" name="answer_editor_textbox" class="wysiwyg " style="width:98%">
				'.$messageContent.'
			</textarea>
			</div>
			<div class="btn-toolbar">
			<input type="submit" name="send" class="btn btn-warning" id="act-send" value="'.Msg(Messages::BUNDLE,Messages::SEND).'">
			<input type="submit" name="save" class="btn" id="act-save" value="'.Msg(Messages::BUNDLE,Messages::SAVE).'">
			<input type="submit" name="delete" class="btn" id="act-delete" value="'.Msg(Messages::BUNDLE,Messages::DELETE).'">
			</div>';
		$this->screen()->add(new \Fox\Html\Html('ht',$htmlAnswer));
		$hide = ($this->hidden) ? 'hide' : null;
		$html .= '<div class="message-answer '.$hide.'" id="answer-complete-box" >';
			
		
		switch($this->renderingMode) {
			case self::RENDERING_MODE_ANSWER :
				$html .='<ul class="nav nav-tabs" id="answer-tabs">
			  				<li class="active"><a href="#m_answer" id="tab_answer">'.Msg(Messages::BUNDLE,Messages::ANSWER).'</a></li>
			 				 <li><a href="#m_forward" id="tab_forward">'.Msg(Messages::BUNDLE,Messages::FORWARD).'</a></li>
						</ul>';
				break;
			case self::RENDERING_MODE_FORWARD :
				$html .='<ul class="nav nav-tabs" id="answer-tabs">
			  				<li class="active"><a href="#m_answer" id="tab_answer">'.Msg(Messages::BUNDLE,Messages::ANSWER).'</a></li>
			 				 <li><a href="#m_forward" id="tab_forward">'.Msg(Messages::BUNDLE,Messages::FORWARD).'</a></li>
						</ul>';
				break;
			default:
				break;	
		}
		$html .= $this->screen()->render();
		$html .= '</div>';
		return '<div class="message-answer-container">'.$html.'</div>';
	}
	
	/**
	 * Parse Posted Information
	 * @
	 */
	public function parsePostResult() {
		$xview = \Xview::instance();
		$inputs = $_POST;
		$anwserid = $xview->val('anwserid');
		if($_POST['pushed'] == 'act-delete') {
			if(!empty($anwserid)) {
				try {
					$answerMessage = \Fox\Dao::load(\Orx\Mailer\MailBox\Message::className(),$anwserid);
				} catch(Fox\Object\Exception\NotExist $e) {
					$answerMessage = new \Orx\Mailer\MailBox\Message(); 
				}
				$inputs['status'] = \Orx\Mailer\MailBox\Message::STATUS_DELETED;
				$answerMessage->setFields($inputs);
				if($answerMessage->exists()) {
					$answerMessage->delete();
				}
			}
			$_SESSION['deletion'] = true;
			\Fox\Message::Success(Msg(\Orx\Mailer\Messages::BUNDLE,\Orx\Mailer\Messages::MESSAGE_HAS_BEEN_DELETED));
			return;
		}
		$headerPart = $this->headerPart()->get();
		if(empty($inputs['receivers']) && empty($inputs['ccs']) && empty($inputs['cci'])) {
			\Fox\Message::Error(Msg(Messages::BUNDLE,Messages::ERR_NEED_AT_LEAST_ONE_RECEIVER));
		}
		
		if(!$this->screen()->errors()) {
			$inputs = array_merge($inputs,$headerPart);
			$xview = \Xview::instance();
			$user = \User::current();
			$editorContent = $_POST['answer_editor_textbox'];
			try {
				$answerMessage = \Fox\Dao::load(\Orx\Mailer\MailBox\Message::className(),$anwserid);
			} catch(Fox\Object\Exception\NotExist $e) {
				$answerMessage = new \Orx\Mailer\MailBox\Message(); 
			}
			
			if(!$answerMessage->exists()) {
				$inputs['idusr'] = $user->getId();
				$inputs['name'] = $user->name();
				if(!empty($inputs['parentid'])) {
					try {
						$parentMessage = \Fox\Dao::load(\Orx\Mailer\MailBox\Message::className());
						$inputs['thread_index'] = $parentMessage->threadIndex();		
					} catch(\Fox\Object\Exception\NotExist $e) {
						$inputs['parentid'] = null;
						$inputs['thread_index'] = $answerMessage->threadIndex(true);	
					}
				} else {
					$inputs['thread_index'] = $answerMessage->threadIndex(true);		
				}
			} else {
				
			}
			foreach($user->personalMailers() as $mailer) {
				if($mailer->email == $inputs['sender']) {
					$inputs['boxid'] = $mailer->boxid;
					$inputs['idusr'] = $mailer->idusr;
					break;
				}
			}
			$inputs['email'] = $inputs['sender'];
			$inputs['received_date'] = \Orx\Mailer\MailBox\Message::sqlDateTime(time());
			$inputs['content'] = trim(strip_tags($editorContent));
			$inputs['content_html'] = trim($editorContent);
			$inputs['reference_class_id'] = \Orx\Mailer\MailBox\Message::MAILBOX_REFERENCE;
			$existingReceivers = array();
			foreach($answerMessage->receivers() as $receiver) {
				$existingReceivers[$receiver->email] = $receiver;
			}
			// Parse Receviers
			$receivers = explode(',',$inputs['receivers']);
			foreach($receivers as $receiverData) {
				$parts = explode(':',$receiverData);
				$email = $parts[0];
				if(empty($email)) {
					continue;
				}
				if(!empty($existingReceivers[$email])) {
					unset($existingReceivers[$email]);
					continue;
				}
				// New Receiver
				$receiver = new \Orx\Mailer\MailBox\Message\Receiver();
				$receiver->email = $email;
				if(!empty($parts[1])) {
					// Its a now contact
					$receiver->name = \Hive\Ressource::fullName($parts[1]);
					$receiver->reference = $parts[1];
					$receiver->reference_class_id = 1;
				}
				$answerMessage->addToReceivers($receiver);
			}
			foreach($existingReceivers as $receiver) {
				$answerMessage->deleteFromReceivers($receiver);
			}
			$existingCci = $existingCcs = array();
			// Parse Carbon Copies
			foreach($answerMessage->carbonCopies() as $receiver) {
				if($receiver->private == 1) {
					$existingCcs[$receiver->email] = $receiver;
				} else {
					$existingCci[$receiver->email] = $receiver;
				}
			}
			// Parse Ccs
			$carbonCopies = explode(',',$inputs['receivers_ccs']);
			foreach($carbonCopies as $receiverData) {
				$parts = explode(':',$receiverData);
				$email = $parts[0];
				if(empty($email)) {
					continue;
				}
				
				if(!empty($existingCcs[$email])) {
					unset($existingCcs[$email]);
					continue;
				}
				// New Receiver
				$receiver = new \Orx\Mailer\MailBox\Message\CarbonCopy();
				$receiver->email = $email;
				$receiver->private = 0;
				if(!empty($parts[1])) {
					// Its a now contact
					$receiver->name = \Hive\Ressource::fullName($parts[1]);
					$receiver->reference = $parts[1];
					$receiver->reference_class_id = 1;
				}
				$answerMessage->addToCarbonCopies($receiver);
			}
			foreach($existingCcs as $receiver) {
				$answerMessage->deleteFromCarbonCopies($receiver);
			}
			// Parse Cci
			$receivers = explode(',',$inputs['receivers_cci']);
			foreach($receivers as $receiverData) {
				$parts = explode(':',$receiverData);
				$email = $parts[0];
				if(empty($email)) {
					continue;
				}
				if(!empty($existingCci[$email])) {
					unset($existingCci[$email]);
					continue;
				}
				
				// New Receiver
				$receiver = new \Orx\Mailer\MailBox\Message\CarbonCopy();
				$receiver->email = $email;
				$receiver->private = 1;
				if(!empty($parts[1])) {
					// Its a now contact
					$receiver->name = \Hive\Ressource::fullName($parts[1]);
					$receiver->reference = $parts[1];
					$receiver->reference_class_id = 1;
				}
				$answerMessage->addToCarbonCopies($receiver);
			}
			foreach($existingCci as $receiver) {
				$answerMessage->deleteFromCarbonCopies($receiver);
			}
			try {
				switch ($_POST['pushed']) {
					case 'act-save': 
						$inputs['status'] = \Orx\Mailer\MailBox\Message::STATUS_DRAFT;
						$answerMessage->setFields($inputs);
						if($answerMessage->exists()) {
							$answerMessage->prepareUpdate(\Orx\Mailer\MailBox\Message::CHANGE_DEFAULT);
							$answerMessage->update();
						} else {
							$answerMessage->create();
						}
						$_SESSION['newmessageid'] = $answerMessage->getId();
						\Fox\Message::Success(Msg(\Orx\Mailer\Messages::BUNDLE,\Orx\Mailer\Messages::MESSAGE_SAVED));
						break;
					
					default:
						$inputs['status'] = \Orx\Mailer\MailBox\Message::STATUS_DRAFT;
						$answerMessage->setFields($inputs);
						// Before Sending we need to create the message
						if($answerMessage->exists()) {
							$answerMessage->prepareUpdate(\Orx\Mailer\MailBox\Message::CHANGE_DEFAULT);
							$answerMessage->update();
						} else {
							$answerMessage->create();
						}
						// Save Data Before Sent
						$_SESSION['sending'] = true;
						// Send Message for Real
						$answerMessage->send();
						$_SESSION['newmessageid'] = $answerMessage->getId();
						if(!\Fox\Message::errors()) {
							\Fox\Message::Success(Msg(\Orx\Mailer\Messages::BUNDLE,\Orx\Mailer\Messages::MESSAGE_SENT));
						}
						break;
				}
			} catch(\Fox\Object\Exception\Save $e) {
				\Fox\Message::Error($e);
			} catch(\Exception $e) {
				\Fox\Message::Error($e);
			}
			
		}
		echo \Xview::instance()->messages(true,true);
		exit;
	}
}